﻿using Microsoft.AspNetCore.Mvc;
using mozhi.smarterp.AuthorCenter.ApiMetadatas;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Guids;

namespace mozhi.smarterp.AuthorCenter.Controllers;

public class HomeController : AbpController
{
    private SwaggerGenerator _swaggerGenerator;

    private IGuidGenerator _guidGenerator;

    private IApiMetadataAppService _apiMetadataAppService;

    public HomeController(SwaggerGenerator swaggerGenerator , IGuidGenerator guidGenerator , IApiMetadataAppService apiMetadataAppService)
    {
        _swaggerGenerator = swaggerGenerator;
        _guidGenerator = guidGenerator;
        _apiMetadataAppService = apiMetadataAppService;
    }

    public ActionResult Index()
    {
        return Redirect("~/swagger");
    }

    public async Task<ActionResult> GenerateApiMatedata()
    {
        var apiDocument = _swaggerGenerator.GetSwagger("v1", "", "");

        var scope = "AuthorCenter";

        if (apiDocument == null || apiDocument.Paths == null)
            return Ok();

        foreach (var path in apiDocument.Paths)
        {
            foreach (var operation in path.Value.Operations)
            {
                var match = await _apiMetadataAppService.FindAsync(scope , path.Key, operation.Key.ToString());

                if (match == null)
                {
                    var apiMetadata = new ApiMetadataCreateDto(path.Key, operation.Key.ToString(), scope);

                    await _apiMetadataAppService.CreateAsync(apiMetadata);
                }
                else
                {
                    var apiMetadata = new ApiMetadataUpdateDto(match.Id, path.Key, operation.Key.ToString(), scope);

                    await _apiMetadataAppService.UpdateAsync(apiMetadata);
                }
            }
        }

        return Ok();
    }
}
